package com.study.socket.notblock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/27 20:14
 */
public class Server
{
    public static void main(String[] args) throws IOException
    {
        ServerSocketChannel open = ServerSocketChannel.open();
        open.configureBlocking(false);
        open.bind(new InetSocketAddress(9898));
        Selector selector = Selector.open();
        open.register(selector, SelectionKey.OP_ACCEPT);

        while (selector.select() > 0)
        {
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext())
            {
                SelectionKey sk = it.next();
                if (sk.isAcceptable())
                {
                    SocketChannel accept = open.accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);
                } else if (sk.isReadable())
                {
                    SocketChannel channel = (SocketChannel) sk.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = channel.read(byteBuffer)) > 0)
                    {
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(),0,len));
                        byteBuffer.clear();
                    }
                }
                it.remove();
            }
        }
    }
}
